//
//  InspectionController.m
//  PropertyMananger
//
//  Created by Mansion on 17/1/21.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "InspectionController.h"
#import "MCSearchBar.h"
#import "InspectionCell.h"
#import "InspectionDetailController.h"
#import "MCSearchBar.h"
#import "MyInspectModel.h"

@interface InspectionController ()<UISearchBarDelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSMutableArray * myInspectListArr;//我的巡检数据源

@end

@implementation InspectionController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self initTitleViewName:@"我的巡检"];
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 55, BHscreenW, BHscreenH-64 - 55) isGroup:NO];
    
    self.myInspectListArr = [[NSMutableArray alloc]init];
    
    [self setupSearchBar];
    
    [self createRefresh];
    
    [self createPlaceHolder];
    
    [self postMyDailyInspectionData];
}
#pragma mark - 创建刷新UI
- (void)createRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.nextPage = 1;
        
        self.isDown = YES;
        //获取数据
        [self postMyDailyInspectionData];
        
    }];
    
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.nextPage += 1;
        
        self.isDown = NO;
        //获取数据
        [self postMyDailyInspectionData];
        
        //    [self.tableView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}

#pragma mark - 搜索框
- (void)setupSearchBar
{
    self.searchBar = [[MCSearchBar alloc] initWithFrame:CGRectMake(15, 7.5, BHscreenW - 30, 35) placeholder:nil];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"请输入日期";
    self.searchBar.barTintColor = BHColor(237, 237, 237);
    [self.view addSubview:self.searchBar];
    [self.searchBar setBackgroundColor:BHColor(237, 237, 237)];
    self.searchBar.layer.cornerRadius = 18.0f;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.layer.borderWidth = 0.5;
    self.searchBar.layer.borderColor = BHColor(237, 237, 237).CGColor;
    self.searchBar.backgroundColor = BHColor(237, 237, 237);
    self.searchText = @"";
    
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.isSearch) {
        return self.resultArr.count;
    }else{
        return self.myInspectListArr.count;
    }
    return 0;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InspectionCell * cell = [InspectionCell cellWithTableView:tableView];
    if (self.isSearch) {
        
        MyInspectModel * model = self.myInspectListArr[indexPath.row];
        cell.timeLabel.text = model.InspectTime;
        cell.contentLabel.text = model.InspectContent;
    }
        MyInspectModel * model = self.myInspectListArr[indexPath.row];
        cell.timeLabel.text = model.InspectTime;
        cell.contentLabel.text = model.InspectContent;
    
    return cell;
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UITableViewHeaderFooterView * headerView =[[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"header"];
    
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    InspectionDetailController * detailVC = [[InspectionDetailController alloc]init];
    
    detailVC.model = self.myInspectListArr[indexPath.row];
    
    [self.navigationController pushViewController:detailVC animated:YES];

}
#pragma mark - 搜索代理方法
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if (range.location == 0) {
        
        [self.resultArr removeAllObjects];
        [self.tableView reloadData];
    }
    return YES;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    self.isDown = YES;
    [self postMyDailyInspectionData];
    
    [self.tableView.mj_header beginRefreshing];

    
    [self.view endEditing:YES];

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    DLog(@"点击取消");
    self.isSearch = NO;
   
    self.searchStr = @"";
    
    self.isDown = YES;
    self.nextPage = 1;
    
    [self postMyDailyInspectionData];

    
//    [self.tableView reloadData];
    
    [searchBar resignFirstResponder];
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
   // [self postMyDailyInspectionData];
    
    [self.searchBar resignFirstResponder];
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.tableView endEditing:YES];
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
    self.isSearch = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length == 0) {
        
        self.searchText = @"";
        self.isSearch = NO;
        self.placehoderImg.hidden = NO;
        self.titleLabel.hidden = NO;
        
        [self.tableView.mj_header beginRefreshing];
        [self.tableView reloadData];
    }
    
    self.placehoderImg.hidden = NO;
    self.titleLabel.hidden = NO;
    
     self.searchStr = searchText;
    [self.resultArr removeAllObjects];
    [self.myInspectListArr removeAllObjects];
    
    [self.tableView reloadData];
    
    for (MyInspectModel * model in self.myInspectListArr) {
        if ([model.InspectTime rangeOfString:searchText].location != NSNotFound) {
            [self.resultArr addObject:model.InspectTime];
        }
    }
    
    if (self.resultArr.count != 0) {
        self.isSearch = YES;
        self.placehoderImg.hidden = YES;
        self.titleLabel.hidden = YES;
        [self.tableView reloadData];
    }

}
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar{

    DLog(@"点击清除按钮");
}
#pragma mark - 数据请求
- (void)postMyDailyInspectionData{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"努力加载数据中...";
    // 隐藏时从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.userInteractionEnabled = YES;
    NSDictionary * parms = nil;
    if (self.searchStr != nil) {
        
        parms =  @{
                                  @"CommunityID":userModel.CommunityID,
                                  @"WorkerId":userModel.WorkerID,
                                  @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                                  @"InspectTime":self.searchStr,
                                  @"json":@"\{\"jsonEntity\":\{},\"action\":\"showinspect\",\"version\":\"V1.0\"}"
                                  };
        
    }else{
    
       parms =  @{
                                  @"CommunityID":userModel.CommunityID,
                                  @"WorkerId":userModel.WorkerID,
                                  @"Page":[NSString stringWithFormat:@"%ld",self.nextPage],
                                  @"InspectTime":@"",
                                  @"json":@"\{\"jsonEntity\":\{},\"action\":\"showinspect\",\"version\":\"V1.0\"}"
                                  };
    }
   
    DLog(@"提交的参数 === %@",parms);
    
    [MineRequest postMyDailyInspectionSuccess:^(id data) {
        
        if (self.isDown == YES) {
            
            [self.myInspectListArr removeAllObjects];
            self.isDown = NO;
        }
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"返回 === %@",dict[@"Code"]);
        DLog(@"返回提示 === %@",dict[@"Msg"]);
        DLog(@"我的日常巡检数据 == %@",array);
        
        for (NSDictionary * dict in array) {
            
            MyInspectModel * model = [[MyInspectModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.myInspectListArr addObject:model];
            
        }
        
        if (self.myInspectListArr.count != 0){
            
            self.placehoderImg.hidden = YES;
            self.titleLabel.hidden = YES;
            
        }else{
            
//            self.tableView.mj_footer.hidden = YES;
            
            self.placehoderImg.hidden = NO;
            self.titleLabel.hidden = NO;
        }
        
//        if (self.myInspectListArr.count <=4) {
//            self.tableView.mj_footer.hidden = YES;
//        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUDForView:self.view];
        
        [self.tableView reloadData];
    } Fail:^(NSString *errorDes) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUD];
        
    } param:parms ];
    
}
#pragma mark - 暂未图
- (void)createPlaceHolder
{
    
    self.placehoderImg = [[UIImageView alloc]init];
    [self.tableView addSubview:self.placehoderImg];
    self.placehoderImg.image = [UIImage imageNamed:@"ico_patrol_empty"];
    
    [self.placehoderImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.tableView.mas_bottom).with.offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    self.titleLabel = [[UILabel alloc]init];
    [self.tableView addSubview:self.titleLabel];
    self.titleLabel.text = @"暂无巡检";
    
    self.titleLabel.textColor= BHColor(153, 153, 153);
    self.titleLabel.font = BHFont(15);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.tableView).with.offset(0);
        make.top.equalTo(self.placehoderImg.mas_bottom).with.offset(10);
        make.size.mas_equalTo(CGSizeMake(100, 25));
    }];
    
}

@end
